package com.tengju.settlement.infrastructure.repository.convert;

import com.tengju.settlement.domain.model.account.UserIdCode;
import com.tengju.settlement.domain.model.depository.*;
import com.tengju.settlement.domain.shared.IdObject;
import com.tengju.settlement.infrastructure.persistence.mybatis.dataobject.DepositoryBankCardDO;
import com.tengju.user.domain.shared.JsonUtil;

import java.time.LocalDateTime;
import java.util.Optional;

public class DepositoryBankCardConvert {

    public static DepositoryBankCard convertToModel(DepositoryBankCardDO depositoryBankCardDO) {
        if (depositoryBankCardDO == null) {
            return null;
        }

        BankCardExtra bankCardExtra = JsonUtil.toObject(depositoryBankCardDO.getExtra(), BankCardExtra.class);

        return new DepositoryBankCard(
                new DepositoryBankCardId(depositoryBankCardDO.getId()),
                new UserIdCode(depositoryBankCardDO.getIdCode()),
                new DepositoryAccountId(depositoryBankCardDO.getDepositoryAccountId()),
                BankCardType.ofInnerCode(depositoryBankCardDO.getCardType()),
                depositoryBankCardDO.getCardNo(),
                depositoryBankCardDO.getBankName(),
                depositoryBankCardDO.getSuperBankNo(),
                BindStatus.fromVal(depositoryBankCardDO.getBindStatus()),
                bankCardExtra
        );
    }

    public static DepositoryBankCardDO convertToDO(DepositoryBankCard depositoryBankCard) {
        if (depositoryBankCard == null) {
            return null;
        }
        DepositoryBankCardDO depositoryBankCardDO = new DepositoryBankCardDO();
        depositoryBankCardDO.setId(Optional.ofNullable(depositoryBankCard.getDepositoryBankCardId()).map(IdObject::getValue).orElse(null));
        depositoryBankCardDO.setIdCode(Optional.ofNullable(depositoryBankCard.getIdCode()).map(IdObject::getValue).orElse(0L));
        depositoryBankCardDO.setDepositoryAccountId(Optional.ofNullable(depositoryBankCard.getDepositoryAccountId()).map(IdObject::getValue).orElse(0L));
        depositoryBankCardDO.setCardType(Optional.ofNullable(depositoryBankCard.getCardType()).map(BankCardType::getInnerVal).orElse(0));
        depositoryBankCardDO.setCardNo(depositoryBankCard.getCardNo());
        depositoryBankCardDO.setBankName(depositoryBankCard.getBankName());
        depositoryBankCardDO.setSuperBankNo(depositoryBankCard.getSuperBankNo());
        depositoryBankCardDO.setBindStatus(depositoryBankCard.getStatus().getVal());
        depositoryBankCardDO.setExtra(JsonUtil.toJSONString(depositoryBankCard.getExtra()));
        depositoryBankCardDO.setCreateTime(LocalDateTime.now());
        depositoryBankCardDO.setUpdateTime(LocalDateTime.now());
        return depositoryBankCardDO;
    }
}
